<!-- 
基建出库——根据原单生成

-->
<template>
  <div>
    <!-- 原单生成按钮和表格 -->
    <a-button type="primary" style="margin-top: 20px" @click="showModal">
      <a-icon type="plus" />
      根据{{ this.ModalTitlePlus }}生成
    </a-button>
    <a-modal
      :title="ModalTitleBiaoTiao"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      width="70%"
    >
      <!-- 搜索表单---查询条件 -->
      <a-form v-bind="layout">
        <a-row>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="时间段">
              <a-range-picker
                v-model="searchForm.rangeDate"
                @change="getRangeTime"
              />
            </a-form-item>
          </a-col>

          <!-- 申请部门=下拉框 -->
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="申请部门">
              <a-tree-select
                v-model="searchForm.applicationDept_text"
                show-search
                style="width: 100%"
                :tree-data="depTree"
                allow-clear
                @change="changeTreeNode"
              ></a-tree-select>
              <!-- <a-tree-select
                v-model="searchForm.departmentName"
                show-search
                style="width: 100%;"
                :tree-data="depTree"
                allow-clear
                @change="onChangeBumen"
              ></a-tree-select> -->
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-item label="单据状态">
              <a-select
                v-model="searchForm.documentClosed"
                showSearch
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in danJvZhuangTaiList"
                  :key="item"
                  :value="item"
                  >{{ item }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <a-form-model-item label="单据编号">
              <a-select
                v-model="searchForm.document"
                style="width: 100%"
                showSearch
              >
                <a-select-option
                  v-for="(item, index) in SourceOrderList"
                  :key="index"
                  :value="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :xl="24"
            :lg="24"
            :md="24"
            :sm="24"
            :xs="24"
            :style="{ textAlign: 'right' }"
          >
            <a-button type="primary" @click="getsearch1()">查询</a-button>
            <a-button style="margin-left: 8px" @click="Reset()">重置</a-button>
          </a-col>
        </a-row>
      </a-form>

      <!-- 上半部分表格 -->
      <a-table
        :columns="orderColumns"
        :data-source="orderDataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :row-selection="{
          selectedRowKeys: orderSelectedRowKeys,
          onChange: orderOnSelectChange,
          type: 'radio',
          getCheckboxProps: getCheckboxProps,
        }"
      >
        <template slot="action" slot-scope="text, record">
          <!-- <span v-if="record.flagUp">
            <a @click="cancle(record.key)">已开启</a>
          </span> -->
          <a-popconfirm
            v-if="record.flagUp"
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onChangeUp(record)"
          >
            <template slot="title">
              <p>是否关闭单据?</p>
            </template>
            <a href="javascript:;"> 开启 </a>
          </a-popconfirm>
          <a-popconfirm
            v-else
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onChangeUp(record)"
          >
            <template slot="title">
              <p>是否开启单据?</p>
            </template>
            <a href="javascript:;"> 关闭 </a>
          </a-popconfirm>
        </template>
      </a-table>
      <a-divider dashed />

      <!-- 下半部分：物品表格 -->
      <a-table
        style="margin-top: 10px"
        :columns="listColumns"
        :data-source="ListDataSource"
        :pagination="false"
        :row-selection="{
          selectedRowKeys: listSelectedRowKeys,
          onChange: listOnSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
        :scroll="{ x: 1500 }"
      >
        <template slot="action" slot-scope="text, record">
          <!-- <span v-if="record.flagUp">
            <a @click="cancle(record.key)">已开启</a>
          </span> -->
          <a-popconfirm
            v-if="record.flagUp"
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onChangeDown(record)"
          >
            <template slot="title">
              <p>是否关闭单据?</p>
            </template>
            <a href="javascript:;"> 开启 </a>
          </a-popconfirm>
          <a-popconfirm
            v-else
            ok-text="确定"
            cancel-text="取消"
            @confirm="() => onChangeDown(record)"
          >
            <template slot="title">
              <p>是否开启单据?</p>
            </template>
            <a href="javascript:;"> 关闭 </a>
          </a-popconfirm>
        </template>
      </a-table>

      <!-- 备货通知单物品信息 -->
    </a-modal>
  </div>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

import { JiJianChuKuHttp } from "@/services/modules/ChuKuGuanLi/JJianChuKu/JiJianChuKu";
const JiJianChuKu = new JiJianChuKuHttp(); // 基建出库

export default {
  props: {
    // 对话框标题
    ModalTitle: {
      type: String,
      required: true,
    },

    // 表单列
    orderColumns: {
      type: Array,
      required: true,
    },
    // 列表列
    listColumns: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      SourceOrderList: [], //源单单号列表

      danJvZhuangTaiList: ["开启", "关闭"],
      id: "", //上方表格选中的id
      depTree: [], // 部门列表

      pagination: {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        // pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
        pageSizeOptions: ["5", "10", "20"], //每页中显示的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
      },

      visible: false,

      searchForm: {
        document: "",
        rangeDate: null,
        departmentName: "",
        departmentId: "",
        documentClosed: "开启",
      },

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 15 },
      },

      orderSelectedRowKeys: [], // 上方表格选中按钮
      orderDataSource: [], //上方表格数据源

      listSelectedRowKeys: [], // 下方表格选中按钮
      ListDataSource: [], //下方表格数据源

      getselectedRows: [], //表格选中数据

      beginTime: "", // 开始时间
      endTime: "", // 结束时间
      // saleDepartmentList: [], // 销售部门列表

      // showType: false,
      // showTypejijian: false,
      // showTypeqita: false,

      ModalTitleBiaoTiao: "",
      ModalTitlePlus: "源单",

      originData: [],
      // SourceId:"",//源单单号id
      SourceName: "", //源单单号string(外键)
      applicationDeptId: "", //申请部门id
      applicationDeptName: "", //申请部门name

      projectsUnderConstruction: "", //在建项目id
      projectsUnderConstruction_text: "", //在建项目name
    };
  },
  mounted() {
    this.getDeparmentTree(); //获取部门树
    // this.getsearch1();
    this.getList();
    this.getSourceOrderList(); //获取单据号列表
  },

  methods: {
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.documentClosed == "关闭",
        },
      };
    },
    //关闭上方单据
    onChangeUp(record) {
      let flag;
      if (record.documentClosed == "开启") {
        flag = "关闭";
      } else {
        flag = "开启";
      }
      let data = {
        id: record.id,
        documentClosed: flag,
      };
      console.log("data", data);
      comHttp.updateJiJian(data).then((res) => {
        console.log("res", res);
        if (res.success) {
          this.$message.success("成功！");
          this.getList();
        }
      });
    },
    //关闭下方单据
    onChangeDown(record) {
      let flag;
      if (record.documentClosed == "开启") {
        flag = "关闭";
      } else {
        flag = "开启";
      }
      let data = {
        id: record.id,
        documentClosed: flag,
      };
      console.log("data", data);
      comHttp.updateJiJianBiaoDan(data).then((res) => {
        console.log("res", res);
        if (res.success) {
          this.$message.success("成功！");
          this.getWuPin(this.id);
        }
      });
    },
    //根据上方选中数据id查询下方物品
    getWuPin(id) {
      this.ListDataSource = [];
      JiJianChuKu.getcreateBySourceById("?id=" + id).then((res) => {
        console.log("表格选择事件res", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            id: res.result.list[i].id,
            key: i + 1, //序号
            storageUnit_dictText: res.result.list[i].storageUnit_dictText, //所属单位name
            subordinate_text1: res.result.list[i].storageUnit, //所属单位id

            depotId: res.result.list[i].depotId, //仓库编码id
            depotNo: res.result.list[i].depotNo, //仓库编码
            depotId_dictText: res.result.list[i].depotId_dictText, //仓库名称

            inventoryNo: res.result.list[i].inventoryNo, //存货编码
            inventoryId: res.result.list[i].inventoryId, //存货编码
            inventoryNane: res.result.list[i].inventoryName, //存货名称
            standardModel: res.result.list[i].standardModel, //!规格型号,
            unit: res.result.list[i].unit, //单位
            // applyNumber: res.result.list[i].requisitionNo, //申请数量
            actualQuantity: res.result.list[i].actualQuantity, //实发数量
            remarks: res.result.list[i].remarks, //备注
            sourceNumber: this.SourceName, //源单单号
            applicationDept: this.applicationDeptId, //申请部门id
            applicationDept_text: this.applicationDeptName, //申请部门name
            projectsUnderConstruction: this.projectsUnderConstruction, //在建项目id
            projectsUnderConstruction_dictText:
              this.projectsUnderConstruction_dictText, //在建项目name
            documentClosed: res.result.list[i].documentClosed, //单据状态
            // flagUp: res.result.list[i].documentClosed == "开启" ? true : false,
          };
          if (res.result.list[i].documentClosed !== "关闭")
            data[`flagUp`] = true;
          this.ListDataSource.push(data);
        }
        console.log("this.ListDataSource", this.ListDataSource);
      });
    },
    //获取上方表格每条记录的单据状态
    // getdocumentClosedUp(array) {
    //   let flagUp;
    //   array.forEach((element) => {
    //     if (element.documentClosed == "开启") {
    //       this.$set(element, flagUp, true);
    //     } else {
    //       this.$set(element, flagUp, false);
    //     }
    //   });
    // },
    // 获取部门列表
    getDeparmentTree() {
      console.log("获取部门列表hanshu===");
      comHttp.getDepartmentList().then((res) => {
        this.depTree = res.result;
        console.log(this.depTree, "111111111111111111");
        this.changeCorpData(this.depTree);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
        // element["title"] = element.deptname;
        // element["children"] = element.syncDepartmentFilesEntityList;
        // element["key"] = element.pkDeptdoc;
        // element["value"] = element.pkDeptdoc;

        // if (element.children) {
        //   this.changeCorpData(element.children);
        // }
      });
    },
    // 获取源单号列表
    getSourceOrderList() {
      let queryPath = "?string=JJSQ-";
      comHttp.getSourceNumber(queryPath).then((res) => {
        console.log("获取生产领料单源单列表:::::", res);
        for (let i = 0; i < res.result.length; i++) {
          this.SourceOrderList.push(res.result[i]);
        }
      });
    },
    // 部门下拉框选择
    changeTreeNode(a) {
      console.log("a", a);
      let array = a.split("|");

      this.searchForm.applicationDeptId = array[0];
      this.searchForm.applicationDept = array[1];
      this.searchForm.applicationDept_text = array[1];
    },
    // changeTreeNode(key, value) {
    //   console.log("key", key);
    //   console.log("value", value);
    //   this.searchForm.applicationDeptId = key;
    //   this.searchForm.applicationDept = value[0];
    //   console.log("选择的值::::", this.searchForm.applicationDept);
    //   console.log(
    //     "选择的applicationDeptId值::::",
    //     this.searchForm.applicationDeptId
    //   );
    // },
    // 部门字典表中每一项vlaue 变成 title 为了方便搜索
    // resetDepartmentTree(dep) {
    //   dep.forEach((item) => {
    //     item.value = item.title;
    //     if (item.children) {
    //       this.resetDepartmentTree(item.children);
    //     }
    //   });
    // },
    // 部门下拉框选择
    //根据提交部门的title，找到对应value,并给部门id赋值
    // onChangeBumen(value, b, c, d) {
    //   console.log("value", value);
    //   console.log("b", b);
    //   console.log("c", c);
    //   console.log("d", d);
    //   console.log("this.searchForm", this.searchForm);
    //   // this.form.bumen = [];
    //   // this.form.bumen = value;
    //   comHttp.getdepartmentlistTree().then((res) => {
    //     console.log("res.result.children", res.result[0].children);
    //     let array = res.result[0].children;
    //     console.log("array!", array);
    //     for (let i = 0; i < array.length; i++) {
    //       console.log("进入1");
    //       if (array[i].title == value) {
    //         this.searchForm.departmentId = array[i].key;
    //         this.searchForm.departmentName = array[i].title;
    //         console.log("这是最终的searchForm", this.searchForm);
    //       }
    //     }
    //   });
    // },

    //————————————————————————分页查询：开始——————————————————————————————
    // ---------- 分页函数 -------------
    handleTableChange(pagination) {
      console.log("pagination===========>", pagination);
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;

      this.Search();
    },
    // 1. 获取列表函数,该函数的作用是获取页面上显示的表格
    // 获取列表设置默认参数:分页为 1 的参数
    getList(queryPath = "?pageNo=1&pageSize=5&documentClosed=开启") {
      // getList(queryPath) {
      console.log("我进来了！");

      JiJianChuKu.getJiJianYuanDan(queryPath).then((res) => {
        console.log("res列表getJiJianYuanDan:::", res);
        this.orderDataSource = []; // 重置 table 的 dataSource 数据
        // 设置分页
        const pagination = { ...this.pagination };
        pagination.total = res.result.total;
        pagination.pageSize = res.result.size;
        this.pagination = pagination;
        // 渲染数据,把接收的数据渲染到table中
        //  this.orderDataSource = res.result.records;
        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            id: res.result.records[i].id,
            key: (res.result.current - 1) * 5 + i + 1, //序号
            requisitionNo: res.result.records[i].requisitionNo, //申请单号
            applicationDate: res.result.records[i].applicationDate, //申请日期
            applicationDepot_text:
              res.result.records[i].applicationDept_dictText, //申请部门
            applicationDept: res.result.records[i].applicationDept, //申请部门id
            applicant_text: res.result.records[i].applicant_dictText, //申请人
            applicant: res.result.records[i].applicant, //申请人id
            // sendReceiveType_text:res.result.records[i].sendReceiveType_dictText, //收发类别
            // sendReceiveType: res.result.records[i].sendReceiveType, //收发类别id
            projectsUnderConstruction_dictText:
              res.result.records[i].projectsUnderConstruction_dictText, //在建项目
            projectsUnderConstruction:
              res.result.records[i].projectsUnderConstruction, //在建项目id
            documentClosed: res.result.records[i].documentClosed, //单据状态
            // flagUp:res.result.records[i].documentClosed == "开启" ? true : false,
          };
          if (res.result.records[i].documentClosed !== "关闭") {
            data[`flagUp`] = true;
          }
          this.orderDataSource.push(data);
        }
        console.log("this.orderDataSource", this.orderDataSource);
      });
    },

    // 2. 获取查询条件 函数,该函数会返回当前的查询条件， 搜索栏查询条件 + 分页的页码
    getQueryPath() {
      if (this.searchForm.applicationDeptId == undefined) {
        this.searchForm.applicationDeptId = "";
      }
      let queryPath =
        "?pageNo=" +
        this.queryParam.page +
        "&pageSize=" +
        this.queryParam.size +
        "&beginDate=" +
        // "?beginDate=" +
        this.beginTime +
        "&endDate=" +
        this.endTime +
        "&deptId=" +
        this.searchForm.applicationDeptId +
        "&documentClosed=" +
        this.searchForm.documentClosed +
        "&document=" +
        this.searchForm.document;
      return queryPath; // 返回的查询条件
    },
    // 3. 重置当前页码及页码参数
    resetPagination() {
      this.pagination = {
        total: 0,
        current: 1,
        pageSize: 5, //每页中显示10条数据
        showSizeChanger: true,
        // pageSizeOptions: ["5"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      };
      //查询参数
      this.queryParam = {
        //查询参数
        page: 1, //第几页
        size: 5, //每页中显示数据的条数
      };
    },

    // 4、查询按钮触发函数——单独写，目的是在页码不为1时，点击查询，页码自动归1
    getsearch1() {
      this.resetPagination(); //重置页码和参数
      //重置按钮触发函数
      // this.resetForm();
      // 获取目前选择好的查询条件
      let queryPath = this.getQueryPath();
      console.log("当前的查询路径为:::", queryPath);
      this.getList(queryPath);
      // this.resetPagination(); // 查询完后 需要重置页码和参数
    },
    // 5. 供分页调用的查询函数
    Search() {
      // 获取目前选择好的查询条件
      let queryPath = this.getQueryPath();
      // console.log("当前的查询路径为:::",queryPath);
      this.getList(queryPath);
      //this.resetPagination(); // 查询完后 需要重置页码和参数
    },
    // 6. 重置按钮触发函数
    resetForm() {
      // 重置查询表单,动态刷新列表
      this.searchForm = {
        document:"",
        rangeDate: null,
        departmentName: "",
        departmentId: "",
      };
      // this.resetPagination(); //需要重置页码和参数
      // 重新调用获取列表函数，默认参数获取列表
      this.getList();
    },

    //————————————————————————分页查询：结束——————————————————————————————
    // ---------- 搜索表单函数 ----------
    // 根据业务需求,自己添加相应的样式和函数

    // 时间段
    getRangeTime(date, dateString) {
      this.beginTime = dateString[0];
      this.endTime = dateString[1];
      console.log(this.beginTime);
      console.log(this.endTime);
    },

    // 重置
    Reset() {
      this.resetPagination(); // 重置分页情况

      this.searchForm = {
        document:"",
        rangeDate: null,
        departmentName: "",
        departmentId: "",
        documentClosed: "",
      };
      this.startTime = "";
      this.endTime = "";
      this.ListDataSource = [];
      this.orderDataSource = [];
      this.getList();
    },
    // 展示对话框
    showModal() {
      this.getList();
      // 销售部门列表
      // this.getSaleDepartmentList();

      // 如果传递过来的是销售订单,样式更换为::::::
      // if (this.ModalTitle == "销售订单") {
      //   this.showType = true;
      // } else
      if (this.ModalTitle == "基建原单") {
        // this.showTypejijian = true;
        this.ModalTitleBiaoTiao = "基建出库申请单生成基建出库单";
      } else if (this.ModalTitle == "其他原单") {
        // this.showTypeqita = true;
        this.ModalTitleBiaoTiao = "其他出库申请单生成其他出库单";
      }
      this.visible = true;
    },
    // 提交
    handleOk() {
      console.log("提交");
      this.$emit("origin-data", this.originData); //将子组件的数据，传递到父组件
      this.orderSelectedRowKeys = []; // 上方表格选中按钮
      this.listSelectedRowKeys = []; // 下方表格选中按钮
      this.ListDataSource = []; //下方表格数据源
      this.visible = false;
    },
    // 清空
    // Empty() {
    //   this.ListDataSource = [];
    //   console.log("清空");
    // },
    // 取消
    handleCancel() {
      // this.$emit("origin-data", this.originData); //将子组件的数据，传递到父组件
      this.visible = false;
    },
    // 表格选择事件,
    orderOnSelectChange(selectedRowKeys, selectedRows) {
      this.listSelectedRowKeys = []; //清空下方表格的选择样式
      this.originData = []; //清空下方表格选中的数据

      this.ListDataSource = [];
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      console.log("selectedRows changed: ", selectedRows); //获取表格中一行数据
      let id = selectedRows[0].id;
      this.id = selectedRows[0].id;
      console.log("id", id);

      // this.SourceId=selectedRows[0].sourceNumber;//源单单号id
      this.SourceName = "";
      this.applicationDeptId = "";
      this.applicationDeptName = "";
      this.projectsUnderConstruction = "";
      this.projectsUnderConstruction_text = "";
      this.SourceName = selectedRows[0].requisitionNo; //源单单号name
      this.applicationDeptId = selectedRows[0].applicationDept; //申请部门id
      this.applicationDeptName = selectedRows[0].applicationDepot_text; //申请部门name
      this.projectsUnderConstruction =
        selectedRows[0].projectsUnderConstruction; //在建项目id
      this.projectsUnderConstruction_dictText =
        selectedRows[0].projectsUnderConstruction_dictText; //在建项目name

      JiJianChuKu.getcreateBySourceById("?id=" + id).then((res) => {
        console.log("表格选择事件res", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            id: res.result.list[i].id,
            key: i + 1, //序号
            storageUnit_dictText: res.result.list[i].storageUnit_dictText, //所属单位name
            subordinate_text1: res.result.list[i].storageUnit, //所属单位id

            depotId: res.result.list[i].depotId, //仓库编码id
            depotNo: res.result.list[i].depotNo, //仓库编码
            depotId_dictText: res.result.list[i].depotId_dictText, //仓库名称

            inventoryNo: res.result.list[i].inventoryNo, //存货编码
            inventoryId: res.result.list[i].inventoryId, //存货编码
            inventoryName: res.result.list[i].inventoryName, //存货名称
            standardModel: res.result.list[i].standardModel, //!规格型号,
            unit: res.result.list[i].unit, //单位
            // applyNumber: res.result.list[i].requisitionNo, //申请数量
            actualQuantity: res.result.list[i].actualQuantity, //实发数量
            remarks: res.result.list[i].remarks, //备注
            sourceNumber: this.SourceName, //源单单号
            applicationDept: this.applicationDeptId, //申请部门id
            applicationDept_text: this.applicationDeptName, //申请部门name
            projectsUnderConstruction: this.projectsUnderConstruction, //在建项目id
            projectsUnderConstruction_dictText:
              this.projectsUnderConstruction_dictText, //在建项目name
            documentClosed: res.result.list[i].documentClosed, //单据状态
            flagUp: res.result.list[i].documentClosed == "关闭" ? false : true,
          };
          // if (res.result.records[i].documentClosed !== "关闭") {
          //   data[`flagUp`] = true;
          // }
          this.ListDataSource.push(data);
        }
        console.log("this.ListDataSource", this.ListDataSource);
      });
      this.orderSelectedRowKeys = selectedRowKeys;
    },
    // 列表选择事件
    listOnSelectChange(selectedRowKeys, selectedRows) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      console.log("selectedRows changed下方表格的数据: ", selectedRows); //选中的数据
      this.listSelectedRowKeys = selectedRowKeys;
      this.originData = [];
      for (let i = 0; i < selectedRows.length; i++) {
        this.originData.push(selectedRows[i]);
      }
      // this.originData[0].projectsUnderConstruction_text=this.orderDataSource[0].projectsUnderConstruction_text;//在建项目
      // this.originData[0].projectsUnderConstruction=this.orderDataSource[0].projectsUnderConstruction;//在建项目id
    },
  },
};
</script>

<style></style>
